package com.openatc.agent.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

/**
 * @author ：panleilei
 * @description 设备信息缓存
 * @modified By：
 * @version:
 * @date ：Created in 2024/11/8 9:27
 */
@Component
public class DeviceCache {
    private static final Logger logger = Logger.getLogger(DeviceCache.class.getSimpleName());
    private Set<String> deviceIds = new HashSet<>();
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 更新缓存
     */
    public void updateCache() {
        clearCache();
        String sql = String.format("select agentid from dev");
        List<String> agentIds = jdbcTemplate.queryForList(sql, String.class);
        logger.info("update device cache.device size: " + agentIds.size() +".devices: " + agentIds);
        if (CollectionUtils.isEmpty(agentIds)) return;
        deviceIds.addAll(agentIds);
    }

    /**
     * 清空缓存
     */
    public void clearCache() {
        deviceIds.clear();
    }


    /**
     * 当前缓存中是否存在指定设备
     * @param agentId
     * @return
     */
    public boolean hasDevice(String agentId) {
        if (agentId == null) return false;
        return deviceIds.contains(agentId);
    }

}
